package com.housekeeping.housekeeping.user.dao.impl;

import com.housekeeping.housekeeping.serviceItem.utils.CodeUtils;
import com.housekeeping.housekeeping.user.dao.UserDao;
import com.housekeeping.housekeeping.user.entity.Account;
import com.housekeeping.housekeeping.user.entity.AccountVo;
import com.housekeeping.housekeeping.utils.DBManager;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public int accountExist(String account) throws SQLException {
        int res=0;
        Connection connection= DBManager.getConnection();
        String sql="select count(*) from admins_information where account=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,account);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next())
        {
            res=resultSet.getInt(1);
        }
        DBManager.close(ps,connection,resultSet);
        return res;
    }

    @Override
    public int register(Account account,String sale) throws SQLException {
        int res=0;
        Connection connection=DBManager.getConnection();
        String sql="insert into admins_information(name, account, password, phone_number, classify_id,sale) values (?,?,?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,account.getName());
        ps.setString(2,account.getAccount());
        ps.setString(3, account.getPassword());
        ps.setString(4,account.getPhone());
        ps.setInt(5,account.getClassifyId());
        ps.setString(6,sale);
        res = ps.executeUpdate();
        DBManager.close(ps,connection);
        return res;
    }

    @Override
    public AccountVo login(String account, String password) throws SQLException {
        AccountVo res=null;
        Connection connection = DBManager.getConnection();
        String sql="select password,sale,name,phone_number,classify_id from admins_information where account=? and is_del=0";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,account);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            String pass=resultSet.getString(1);
            String sale=resultSet.getString(2);
            String name=resultSet.getString(3);
            String phone=resultSet.getString(4);
            Integer classify_id=resultSet.getInt(5);
            //密码校验
            if (StringUtils.equals(pass, CodeUtils.md5Hex(password,sale))){
               //密码正确,回传可视账户信息
                res=new AccountVo(name,account,phone,classify_id);
            }
        }
        DBManager.close(ps,connection,resultSet);
        return res;
    }
}
